﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Math;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TInventoryRepository : BaseRepository<TInventory>, ITInventoryRepository
    {
        public TInventoryRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        public List<TInventoryDto> GetTInventoryDtoPage(out int totalCount, int? owerId, int? whId, string? wlName, int? kcState, int pageIndex = 1, int pageSize = 10)
        {
            var list = Context.TInventories.AsNoTracking().ToList();
            if (whId.HasValue)
            {
                list = list.Where(s => s.WarehouseId == whId).ToList();
            }
            if (!string.IsNullOrEmpty(wlName))
            {
                list = list.Where(s => s.MaterialName == wlName).ToList();
            }
            if (kcState.HasValue)
            {
                list = list.Where(s => s.Status == kcState).ToList();
            }
            totalCount = list.Count();

            List<TInventoryDto> paginatedList = new List<TInventoryDto>();
            foreach (var item in list)
            {
                var materialCategoryList = Context.TMaterialCategories.FirstOrDefault(x => x.Id == item.MaterialCategoryId);
                var materialList = Context.TMaterial.FirstOrDefault(x => x.Code == item.MaterialCode);
                TInventoryDto inventoryDto = new TInventoryDto();
                inventoryDto.Id = item.Id;
                inventoryDto.LocationName = item.LocationName;
                inventoryDto.PalletBarcode = item.PalletBarcode;
                inventoryDto.MaterialName = item.MaterialName;
                inventoryDto.AvailableQty = item.AvailableQty;
                inventoryDto.StatusVal = GetInventoryStatus(item.Status);
                inventoryDto.MaterialCode = item.MaterialCode;
                inventoryDto.TotalPrice = item.TotalPrice;
                inventoryDto.Price = item.Price;
                inventoryDto.BatchNoExplain = item.BatchNoExplain;
                inventoryDto.LocationCode = item.LocationCode;
                inventoryDto.ErplocationCode = item.ErplocationCode;
                inventoryDto.SupplierName = item.SupplierName;
                inventoryDto.ExpireDate = item.ExpireDate;
                inventoryDto.ProductDate = item.ProductDate;
                inventoryDto.EquipmentType = materialCategoryList == null ? "无" : materialCategoryList.EquipmentType;
                inventoryDto.MaterialCategoryCode = materialList == null ? "" : materialList.MaterialCategoryCode;
                inventoryDto.MaterialCategoryName = materialList == null ? "" : materialList.MaterialCategoryName;
                inventoryDto.ModelSpec = item.ModelSpec;
                inventoryDto.QualityState = item.QualityState;
                inventoryDto.UnitId = item.UnitId == null ? 0 : item.UnitId;
                inventoryDto.UnitName = item.UnitName == null ? "" : item.UnitName;
                inventoryDto.InventoryQty = item.AvailableQty;
                inventoryDto.CreateDate = item.CreateDate;
                inventoryDto.TotalPrice = item.AvailableQty * item.Price;
                paginatedList.Add(inventoryDto);

            }

            // 分页处理
            paginatedList = paginatedList.OrderByDescending(s => s.CreateDate)
                                    .Skip((pageIndex - 1) * pageSize)
                                    .Take(pageSize)
                                    .ToList();

            return paginatedList;
        }
        public string GetInventoryStatus(int? status)
        {
            string inventoryStatus;

            switch (status)
            {
                case 1:
                    inventoryStatus = "正常库存";
                    break;
                case 2:
                    inventoryStatus = "转移中的库存";
                    break;
                case 3:
                    inventoryStatus = "入库在途";
                    break;
                case 4:
                    inventoryStatus = "出库在途";
                    break;
                case 5:
                    inventoryStatus = "限制使用的库存";
                    break;
                case 6:
                    inventoryStatus = "异常库存";
                    break;
                case 7:
                    inventoryStatus = "预分配库存";
                    break;
                case 8:
                    inventoryStatus = "冻结库存";
                    break;
                default:
                    inventoryStatus = "无";
                    break;
            }

            return inventoryStatus;
        }

        private List<InventoryDetailDto>? GetInventoryDetailDtos(int kqId)
        {
            return Context.TInventoryDetails.AsNoTracking().Where(s => s.InventoryId == kqId).Select(s => new InventoryDetailDto()
            {
                PackageBarcode = s.PackageBarcode,
                Barcode = s.Barcode,
                SkuNum = s.SkuNum,
            }).ToList();
        }

        public List<TInventory> GetTInventoryPage(out int totalCount, int? owerId, int? whId, string? wlName, int pageIndex = 1, int pageSize = 10)
        {
            var list = Context.TInventories.AsNoTracking();


            if (whId.HasValue)
            {
                list = list.Where(s => s.WarehouseId == whId);
            }
            if (!string.IsNullOrEmpty(wlName))
            {
                list = list.Where(s => s.MaterialName.Contains(wlName));
            }

            var res = list.OrderByDescending(x => x.CreateDate)
                        .GroupBy(s => s.MaterialId)
                        .Select(g => new TInventory()
                        {
                            Id = g.First().Id,
                            MaterialCode = g.First().MaterialCode,
                            MaterialName = g.First().MaterialName,
                            TotalPrice = g.First().TotalPrice,
                            AvailableQty = g.Sum(s => s.AvailableQty),
                            LocationCode = g.First().LocationCode,
                            LocationName = g.First().LocationName
                        }).ToList();

            totalCount = res.Count();
            // 分页处理
            var paginatedList = res
                .OrderByDescending(x => x.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                        .Take(pageSize);
            return paginatedList.ToList(); ;
        }




        /// <summary>
        /// 查询所有库存表信息（非分页）
        /// </summary>
        /// <returns></returns>
        public List<TInventory> GetInventoryList()
        {
            var list = Context.TInventories.AsNoTracking();
            return list.OrderBy(r => r.Id).ToList();
        }
        /// <summary>
        /// 导出库存
        /// </summary>
        /// <returns></returns>
        public List<TInventory> GetTInventoryExcel()
        {
            try
            {
                return Context.TInventories.AsNoTracking().ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public List<TMaterialCategory> GetMaterialCategoryGroups()
        {
            try
            {
                return Context.TMaterialCategories.AsNoTracking().ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 器材库存列表
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TInventory> GetXTinventoryList(string mname, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TInventory.AsNoTracking().AsQueryable();

            if (!string.IsNullOrEmpty(mname))
            {
                list = list.Where(x => x.MaterialName.Contains(mname));
            }
            totalCount = list.Count();
            list = list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return list.ToList();
        }


        /// <summary>
        /// 器材目录查询
        /// </summary>
        /// <returns></returns>
        public List<EquipmentQurey> GetEquipmentQureys(int pageIndex, int pageSize, out int totalCount)
        {

            var InventoryList = Context.TInventories.AsQueryable();

            List<EquipmentQurey> equipmentQureys = new List<EquipmentQurey>();

            foreach (var item in InventoryList)
            {
                EquipmentQurey eq = new EquipmentQurey();
                eq.InventoryId = item.Id;
                eq.MaterialCategoryName = item.MaterialCategoryName;
                eq.MaterialName = item.MaterialName;
                eq.MaterialCode = item.MaterialCode;
                eq.ModelSpec = item.ModelSpec;
                eq.QualityState = item.QualityState;
                eq.UnitName = item.UnitName;
                eq.AvailableQty = item.AvailableQty;
                eq.LocationCode = item.LocationCode;
                eq.Price = item.Price;
                eq.TotalPrice = item.TotalPrice;
                eq.CreateTime = item.CreateDate;
                equipmentQureys.Add(eq);
            }
            totalCount = equipmentQureys.Count();
            equipmentQureys = equipmentQureys.OrderByDescending(x => x.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return equipmentQureys;
        }

        /// <summary>
        /// 修改库存质量等级
        /// </summary>
        /// <param name="inventory"></param>
        /// <returns></returns>
        public bool UpInventory(int id, int qualityState, out string msg)
        {
            try
            {
                msg = "";

                var item = Context.TInventories.FirstOrDefault(x => x.Id == id);

                if (item == null)
                {
                    msg = "暂无此库存！";
                    return false;
                }
                if (qualityState == 2 || qualityState == 3)
                {
                    msg = "质量等级只能修改为新品或堪用品！";
                    return false;
                }
                item.QualityState = qualityState;
                Context.Update(item);

                if (Context.SaveChanges() <= 0)
                {
                    return false;
                }
                return true;


            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false; // 或者抛出异常
            }
        }



    }
}
